<?php defined('SYSPATH') or die('No direct script access.');

/**
 *User: idoiwill
 *Email: xslt@idoiwill.com
 *Blog: http://www.idoiwill.com
 *DateTime: 2017/5/15 15:06
 */
class Controller_Pc_Api_Standard_Techan extends Controller_Pc_Api_Base
{
    protected $_typeid = 118;

    public function before()
    {
        parent::before();
    }

    /**
     * @desc 获取轮播图
     */
    public function action_get_xcx_rolling_ad()
    {
        $result = DB::select()->from('xcx_ads')->where('prefix','=','s_techan_index')
            ->order_by('displayorder','asc')->execute()->as_array();
        foreach($result as &$v){
            //判断产品类型
            if($v['typeid'] == 118){
                $v['url'] = '/stpage/techan/pages/show/show';
                $mod = DB::select('litpic')->from('techan');
            }
            if(!empty($mod)){
                $row = $mod ->where('id','=',$v['proid'])->execute()->current();
                //增加图片绝对访问地址
                $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($row['litpic']);
            }
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * @desc 栏目信息
     */
    public function action_channel()
    {
        $result = Model_Api_Standard_Techan::channel();
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }


    public function action_xcx_order_submit()
    {

        $userid = intval($this->request_body->content->userid);
        $linkman = $this->request_body->content->linkman;
        $linktel = $this->request_body->content->linktel;
        $linkemail = $this->request_body->content->linkemail;
        $remark = $this->request_body->content->remark;

        $booknum = intval($this->request_body->content->booknum);
        $suitid = intval($this->request_body->content->suitid);
        $address_id = $this->request_body->content->address_id;
        $croleid =  $this->request_body->content->couponid;

        Common::session('member', array('mid' => $userid));
        //$express_plan_id = $_POST['express_plan_id'];

        $validataion = Validation::factory(array('linkman'=>$linkman,'linktel'=>$linktel));
        $validataion->rule('linktel', 'not_empty');
        $validataion->rule('linktel', 'phone');
        $validataion->rule('linkman', 'not_empty');


        try{
            if (!$validataion->check())
            {
                $error = $validataion->errors();
                $keys = array_keys($validataion->errors());
                throw new Exception(__("error_{$keys[0]}_{$error[$keys[0]][0]}"));
            }

            $suit = ORM::factory('techan_suit')
                ->where("id=:suitid")
                ->param(':suitid', $suitid)
                ->find()
                ->as_array();
            if(empty($suit))
            {
                throw new Exception('套餐不存在');
            }

            $suit['dingjin'] = Currency_Tool::price($suit['dingjin']);
            $suit['achieve_price'] = Currency_Tool::price($suit['achieve_price']);
            $suit['price'] = Currency_Tool::price($suit['price']);

            if (!Model_Techan::check_storage(0, $booknum, $suitid)) {
                throw new Exception('库存不足');
            }
            $product_info = ORM::factory('techan')->where("id",'=',$suit['productid'])->find()->as_array();





            if(!Model_Member_Address::check_address_id($userid, $address_id))
            {
                $address_id = 0;
            }

            $express_total_price = 0;
            if(!empty($suit['freightid']))
            {
                $plan_info = null;
                $plan_info = Model_Express_Plan::get_plan($suit['freightid'],$address_id);

                if($plan_info['status']==0 /*$plan_info['data']['id']!=$express_plan_id*/)
                {
                   throw new Exception('库存不足');
                }
                $express_price = Model_Express_Plan::get_freight_price($suit,$plan_info['data'],$booknum);
                $express_total_price = floatval($express_price);
            }
            $auto_close_time = $suit['auto_close_time'] ? $suit['auto_close_time'] : 0;
            if($auto_close_time)
            {
                $auto_close_time = $auto_close_time + time();
            }
            $achieve_price_total = $suit['achieve_price']*$booknum;
            $ordersn = Product::get_ordersn($this->_typeid);
            $arr = array(
                'ordersn' => $ordersn,
                'webid' => 0,
                'typeid' => $this->_typeid,
                'productautoid' => $product_info['id'],
                'productaid' => $product_info['aid'],
                'productname' => $product_info['title'],
                'litpic' => $product_info['litpic'],
                'price' => $suit['price'],
                'childprice' => 0,
                'jifentprice' => 0,
                'jifenbook' => 0,
                'jifencomment' => 0,
                'paytype' => 1,
                'dingjin' => '',
                'usedate' =>'',
                'departdate' => '',
                'addtime' => time(),
                'memberid' => $userid,
                'dingnum' => $booknum,
                'childnum' => 0,
                'oldprice' => 0,
                'oldnum' => 0,
                'linkman' => $linkman,
                'linktel' => $linktel,
                'linkemail'=>$linkemail,

                'linkidcard' => '',

                'suitid' => $suitid,
                'remark' => $remark,
                'status' => 1,
                'source' => 3,//来源小程序,
                'usejifen' => 0,
                'needjifen' => 0,
                'receiver_address_id' => $address_id,
                'express_total_price' => $express_total_price,
                'auto_close_time' =>$auto_close_time, //自动关闭订单时间,
                'refund_restriction'=>$suit['refund_restriction'],//退改条件
            );


            //优惠券

            if ($croleid)
            {
                $cid = DB::select('cid')->from('member_coupon')->where("id=$croleid")->execute()->current();
                $totalprice = Model_Coupon::get_order_totalprice($arr);
                $ischeck = Model_Coupon::check_samount($croleid, $totalprice, 118, $product_info['id'], null);

                if ($ischeck['status'] == 1)
                {
                    Model_Coupon::add_coupon_order($cid, $ordersn, $totalprice, $ischeck, $croleid); //添加订单优惠券信息
                }
                else {
                   throw new Exception('优惠券不满足使用条件');
                }
            }

            //添加订单

            if (ST_Product::add_order($arr, 'Model_Techan', $arr))
            {
                $orderInfo = Model_Member_Order::order_info($ordersn);
                St_Product::event($ordersn);
            }
            $this->send_datagrams($this->client_info['id'], array('status'=>true,'order'=>$orderInfo), $this->client_info['secret_key']);

        }catch (Exception $excep)
        {
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>$excep->getMessage()), $this->client_info['secret_key']);
        }



    }

    //获取订单详情
    public function action_xcx_order_info()
    {
        $id = $this->request_body->content->id;
        $userid = intval($this->request_body->content->userid);
        $ordersn = DB::select('ordersn')->from('member_order')->where('id','=',$id)->execute()->get('ordersn');
        $row = Model_Member_Order::order_info($ordersn, $userid);

        if(empty($row)){
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'订单不存在'), $this->client_info['secret_key']);
            return;
        }
        //分割订单产品名称
        $tempArr = array_filter(preg_split('`[\(\)]`', $row['productname']));
        $row['subname'] = count($tempArr) > 1 ? $tempArr[count($tempArr) - 1] : '';
        $row['productname'] = str_replace("({$row['subname']})", '', $row['productname']);

        $num = array();
        if ($row['dingnum'] > 0)
        {
            array_push($num, "{$row['dingnum']}个");
        }

        $row['num'] = implode('，', $num);
        //评论
        //封面图

        $product_info = ORM::factory('techan',$row['productautoid'])->as_array();
        $row['litpic'] = Common::img($product_info['litpic']);

        $status=DB::select()->from('techan_order_status')->where('status','=',$row['status'])->and_where('is_show','=',1)->execute()->current();
        $row['statusname']=$status['status_name'];

        if($row['receiver_address_id'])
        {
            $receiver_address = DB::select()->from('member_address')->where('id','=',$row['receiver_address_id'])->execute()->current();
            $row['receiver_address'] =  $receiver_address;

        }
        $row = Pay_Online_Refund::get_refund_info($row);
        $express = DB::select()->from('express_company')->where('pinyin','=',$row['express_company'])->execute()->current();

        $suit = Model_Techan::suit_info($row['suitid']);
        $suit['express_template'] = DB::select()->from('express_template')->where('id','=',$suit['freightid'])->execute()->current();
        $row['suit'] = $suit;
        $row['express'] = $express;

        $row['addtime_fmt'] = date('Y-m-d H:i:s',$row['addtime']);
        $row["web_url"] =  $GLOBALS['cfg_basehost'];
        $this->send_datagrams($this->client_info['id'], $row, $this->client_info['secret_key']);
    }

    public function action_xcx_order_express_confirm()
    {
        $ordersn =$this->request_body->content->ordersn;
        $userid = intval($this->request_body->content->userid);

        $model = ORM::factory('member_order')->where('ordersn','=',$ordersn)->and_where('memberid','=',$userid)->find();

        if(!$model->loaded() || $model->status!='8' || $model->typeid!='118')
        {
            $result = array('status' => false, 'message' => __('错误'));
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            return;
        }

        $model->status = 5;
        $model->save();
        if($model->saved())
        {
            $model->reload();
            $info = $model->as_array();
            Model_Member_Order::back_order_status_changed(8, $info, 'Model_Techan');
            $result=array('status' => true, 'message' => __('已完成'));
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }

    }


    /**
     * @desc 特产
     */
    public function action_xcx_index_list()
    {
        //条数
        $page_size = 10;//intval($this->request_body->content->page_size);
        //页码
       // $page = intval($this->request_body->content->page);


        $out = Model_Api_Standard_Techan::search(null,null,1,$page_size);
        $result = array(
            'data' => $out['list'],
            'total' => $out['total']
        );

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //列表页
    public function action_xcx_search()
    {
        $page_size = 10;//intval($this->request_body->content->page_size);
        $page = intval($this->request_body->content->page);

        $params = array();
        $params['destpy'] = $this->request_body->content->destination;
        $params['sorttype'] = $this->request_body->content->sort_id;
        $params['attrid'] = $this->request_body->content->attrs;
        $keyword = $this->request_body->content->keyword;


        $out = Model_Api_Standard_Techan::search($params,$keyword,$page,$page_size);
        $result = array(
            'data' => $out['list'],
            'total' => $out['total'],
            'list'=>$out['list'],
            'is_finished'=>$out['is_finished']
        );
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }

    public function action_xcx_sort_types()
    {
        $sort_types = array(
                array('id'=>0,'name'=>'综合排序'),
                array('id'=>1,'name'=>'价格由低到高'),
                array('id'=>2,'name'=>'价格由高到低'),
                array('id'=>3,'name'=>'销量优先'),
                array('id'=>4,'name'=>'人气推荐'));
        $this->send_datagrams($this->client_info['id'], $sort_types, $this->client_info['secret_key']);
    }

    public function action_xcx_attr_list()
    {
       $attr_list =  DB::select()->from('techan_attr')->where('isopen','=',1)->and_where('pid','=',0)->execute()->as_array();
       foreach($attr_list as &$attr)
       {
           $attr['child_list'] = DB::select()->from('techan_attr')->where('isopen','=',1)->and_where('pid','=',$attr['id'])->execute()->as_array();
       }
       $this->send_datagrams($this->client_info['id'], $attr_list, $this->client_info['secret_key']);
    }

    /**
     * @desc 特产详情页
     */
    public function action_xcx_show()
    {


        $params['id'] = intval($this->request_body->content->id);
        $productid =  intval($this->request_body->content->productid);
        $params['id'] = empty( $params['id'])?$productid: $params['id'];

        $params['userid'] = intval($this->request_body->content->userid);
        if($params['id'])
        {
            $result = Model_Api_Standard_Techan::detail($params);

            if (empty($result))
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, '查询特产失败', '查询特产失败');
            }
            else
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }

        }

    }

    /**
     * 套餐列表
     */
    public function action_xcx_suit_list()
    {
        $id = intval($this->request_body->content->id);
        $info = DB::select()->from('techan')->where('id','=',$id)->execute()->current();

        $suits = DB::select()->from('techan_suit')->where('productid','=',$id)->execute()->as_array();
        $result = array();
        $selected_suit_id = 0;
        foreach($suits as &$suit)
        {
            $selected_suit_id = $selected_suit_id==0?$suit['id']:$selected_suit_id;
            $express_template = DB::select()->from('express_template')->where('id','=',$suit['freightid'])->execute()->current();
            $min_price = 0;
            if(!empty($express_template))
            {
                $express_template['plan_list'] =  Model_Express_Plan::get_template_planlist($suit['freightid']);
                foreach($express_template['plan_list'] as $plan)
                {
                    $min_price = $min_price==0 || ($min_price>$plan['start_price'] && $plan['start_price']>0)? $plan['start_price']:$min_price;
                }
            }
            $express_template['min_price'] = Currency_Tool::price($min_price);
            $suit['express_template'] = $express_template;

            $suit['price'] = Currency_Tool::price($suit['price']);
            $suit['description'] = Model_Api_Standard_Xcx::filter_content($suit['description']);

            $result[$suit['id']] = $suit;
        }
        $this->send_datagrams($this->client_info['id'], array('suit_list'=>$result,'selected_suit_id'=>$selected_suit_id), $this->client_info['secret_key']);
    }

    public function action_xcx_booking_info()
    {
        $suitid = intval($this->request_body->content->suitid);
        $userid = intval($this->request_body->content->userid);
       // $booknum = intval($this->request_body->content->booknum);
        $suit = Model_Techan::suit_info($suitid);
        $product = DB::select()->from('techan')->where('id','=',$suit['productid'])->execute()->current();
        $suit['product_name'] = $product['title'];

        $this->send_datagrams($this->client_info['id'], array('suit'=>$suit), $this->client_info['secret_key']);
    }

    public function action_xcx_address_list()
    {
        $userid = intval($this->request_body->content->userid);
        $page = intval($this->request_body->content->page);
        $page = $page < 1 ? 1 : $page;
        $page_size = 10;
        $list = DB::select()->from('member_address')->where('memberid', '=',$userid)->order_by('is_default','desc')->order_by('id','desc')->limit($page_size)->offset(($page - 1) * $page_size)->execute()->as_array();
        $this->send_datagrams($this->client_info['id'], array('list'=>$list,'is_finished'=>true), $this->client_info['secret_key']);
    }

    public function action_xcx_address_del()
    {
        $userid = intval($this->request_body->content->userid);
        $id = intval($this->request_body->content->id);
        $del = DB::delete('member_address')->where('memberid', '=',$userid)->and_where('id','=',$id)->execute();
        $result = $del? array('status'=>true):array('status'=>false);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    public function action_xcx_address_info()
    {
        $userid = intval($this->request_body->content->userid);
        $addressid = intval($this->request_body->content->addressid);
        $result = DB::select()->from('member_address')->where('memberid', '=',$userid)->and_where('id','=',$addressid)->execute()->current();
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    public function action_xcx_address_save()
    {
        $userid = intval($this->request_body->content->userid);
        $addressid = intval($this->request_body->content->addressid);
        $city =  $this->request_body->content->city;
        $address =  $this->request_body->content->address;
        $phone =  $this->request_body->content->phone;
        $receiver =  $this->request_body->content->receiver;
        $postcode =  $this->request_body->content->postcode;
        $province =  $this->request_body->content->province;
        $is_default =  $this->request_body->content->is_default;

        if(empty($userid))
        {
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'会员不能为空'), $this->client_info['secret_key']);
            return;
        }

        $model = ORM::factory('member_address')->where('memberid','=',$userid)->and_where('id','=',$addressid)->find();
        $model->memberid = $userid;
        $model->province = $province;
        $model->city = $city;
        $model->address = $address;
        $model->phone = $phone;
        $model->receiver = $receiver;
        $model->postcode = $postcode;
        $model->is_default = $is_default;
        $model->save();
        if($model->saved())
        {
            if($model->is_default==1)
            {
                DB::update('member_address')->set(array('is_default'=>0))->where('memberid','=',$userid)->and_where('id','!=',$model->id)->execute();
            }
            $this->send_datagrams($this->client_info['id'], array('status'=>true), $this->client_info['secret_key']);

        }
        else
        {
            $this->send_datagrams($this->client_info['id'], array('status'=>false,'msg'=>'保存失败'), $this->client_info['secret_key']);
        }


    }

    //获取所有的城市
    public function action_xcx_address_city()
    {
        $list = DB::select()->from('express_destination')->where('pid','=',0)->execute()->as_array();
        foreach($list as &$v)
        {
            $v['children'] = DB::select()->from('express_destination')->where('pid','=',$v['id'])->execute()->as_array();
        }
        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
    }

    public function action_xcx_check_address()
    {
        $suitid = intval($this->request_body->content->suitid);
        $addressid = intval($this->request_body->content->address_id);
        $booknum = intval($this->request_body->content->dingnum);
        $userid = intval($this->request_body->content->userid);

        $suit_info = DB::select()->from('techan_suit')->where('id','=',$suitid)->execute()->current();
        $freightid = $suit_info['freightid'];

        $plan_result = null;
        $plan_result = Model_Express_Plan::get_plan($freightid, $addressid);

        if($plan_result['status']==0)
        {
            $this->send_datagrams($this->client_info['id'],array('status'=>false), $this->client_info['secret_key']);
            return;
        }
        $price = Model_Express_Plan::get_freight_price($suit_info,$plan_result['data'],$booknum);
        $this->send_datagrams($this->client_info['id'],array('status'=>true,'price'=>$price,'plan_id'=>$plan_result['data']['id']), $this->client_info['secret_key']);
    }

    /**
     * @desc 获取报价
     */
    public function action_price()
    {

        $suitid = intval($this->request_body->content->suit_id);
        $suitInfo=Model_Techan_Suit::suit_info($suitid);
        $row = intval($this->request_body->content->row);

        $year = intval($this->request_body->content->year);
        $month = intval($this->request_body->content->month);
        if ($suitid)
        {
            $query = DB::select()->from('techan_ticket_price')->where('ticketid', '=', $suitid);
            if (empty($year) && empty($month))
            {
                $day = strtotime(date('Y-m-d'));
                $query->and_where('day', '>=', $day);
            }
            else
            {
                $need_full_days = true;
                $start = strtotime("$year-$month-1");
                $days = date('t', $start);
                $end = strtotime("$year-$month-$days");
                $query->and_where('day', '>=', $start);
                $query->and_where('day', '<=', $end);
            };
            if ($row)
            {
                $query->limit($row);
            }


            $result = $query->execute()->as_array();

            $now = strtotime(date('Y-m-d'));

            foreach ($result as &$row)
            {
                $row['digital'] = intval(date('d', $row['day']));
                $cur_time=time();
                if(intval($suitInfo['hour_before'])==0&&intval($suitInfo['minute_before'])==0)
                {
                    $offset=24*3600;
                }
                else
                {
                    $offset=3600*intval($suitInfo['hour_before'])+intval($suitInfo['minute_before'])*60;
                }
                $now=$cur_time+intval($suitInfo['day_before'])*24*3600-$offset;
                //过期数据
                if ($row['day'] < $now)
                {
                    $row['adultprice'] = 0;
                    $row['childprice'] = 0;
                    $row['oldprice'] = 0;
                }
                $row['date'] = date('m-d', $row['day']);
                $row['daynum'] = intval(date('d', $row['day']));
                $row['fulldate'] = date('Y-m-d', $row['day']);
                $row['digital'] = intval(date('d', $row['day']));
                $row['adultprice'] = Currency_Tool::price($row['adultprice']);
            }
            if ($need_full_days)
            {
                $insert_day = $days - count($result);
                if ($insert_day)
                {
                    for ($i = 0; $i < $insert_day; $i++)
                    {
                        $r = array(
                            'adultprice' => 0,
                            'childprice' => 0,
                            'oldprice' => 0
                        );
                        array_unshift($result, $r);
                    }
                }
            }

            if (empty($result))
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, '获取最新报价失败', '获取最新报价失败');
            }
            else
            {

                $out = array(
                    'list' => $result
                );
                $this->send_datagrams($this->client_info['id'], $out , $this->client_info['secret_key']);
            }

        }


    }

    /**
     * 创建订单
     */
    public function action_create_order()
    {

        $order = array(
            'webid' => 0,
            'addtime' => time()
        );
        $type_id = $this->_typeid;
        if ($type_id)
        {
            $typeid = intval($type_id);
            $order['typeid'] = $typeid;
            $tmp = intval($typeid) < 10 ? '0' . $typeid : $typeid;
            $ordersn = St_Product::get_ordersn($tmp);
            $order['ordersn'] = $ordersn;

        }
        //产品id
        $product_id = intval($this->request_body->content->product_id);
        if ($product_id)
        {
            $product_id = intval($product_id);
            $order['productautoid'] = $product_id;
            $order['litpic'] = DB::select('litpic')->from('techan')->where('id', '=', $product_id)->execute()->get('litpic');
        }
        //产品aid
        $aid = $this->request_body->content->product_aid;
        if ($aid)
        {
            $productautoaid = intval($aid);
            $order['productaid'] = $productautoaid;
        }
        //产品名称
        $pdt_name = $this->request_body->content->product_name;
        if ($pdt_name)
        {
            $product_name = St_Filter::remove_xss($pdt_name);
            $order['productname'] = $product_name;
        }
        //成人价格
        $adult_price = $this->request_body->content->price;
        if ($adult_price)
        {
            $price = St_Filter::remove_xss($adult_price);
            $order['price'] = $price;
        }
        //联系人信息
        $link_man = $this->request_body->content->link_info->name;
        if ($link_man)
        {
            $linkman = St_Filter::remove_xss($link_man);
            $order['linkman'] = $linkman;
        }

        //联系电话
        $link_tel = $this->request_body->content->link_info->phone;
        if ($link_tel)
        {
            $linktel = St_Filter::remove_xss($link_tel);
            $order['linktel'] = $linktel;
        }
        //email
        $email = $this->request_body->content->link_info->email;
        if ($email)
        {
            $email = St_Filter::remove_xss($email);
            $order['linkemail'] = $email;
        }

        //备注说明
        $re_mark = $this->request_body->content->remark;
        if ($re_mark)
        {
            $remark = St_Filter::remove_xss($re_mark);
            $order['remark'] = $remark;
        }

        //会员id
        $member_id = $this->request_body->content->member_id;
        if ($member_id)
        {
            $memberid = intval($member_id);
            $order['memberid'] = $memberid;
            Common::session('member', array('mid' => $memberid));
        }

        //套餐id
        $suit_id = $this->request_body->content->suit_id;
        if ($suit_id)
        {
            $suitid = intval($suit_id);
            $order['suitid'] = $suitid;
        }
        $suitInfo=Model_Techan_Suit::suit_info($suit_id);
        //成人数量
        $ding_num = $this->request_body->content->ding_num;
        if ($ding_num)
        {
            $dingnum = intval($ding_num);
            $order['dingnum'] = $dingnum;
        }

        //支付方式
        //$pay_type = $this->request_body->content->paytype;
        $pay_type = $suitInfo['paytype'];
        if ($pay_type)
        {
            $paytype = intval($pay_type);
            $order['paytype'] = $paytype;
        }
        //订金金额
        $ding_jin = $this->request_body->content->dingjin;
        if ($ding_jin)
        {
            $dingjin = intval($ding_jin);
            $order['dingjin'] = $dingjin;
        }

        //出发日期
        $use_date = $this->request_body->content->use_date;
        if ($use_date)
        {
            $usedate = $use_date;
            $order['usedate'] = $usedate;
        }
        $couponid = $this->request_body->content->couponid;
        if ($couponid)
        {
            $cid = DB::select('cid')->from('member_coupon')->where("id={$couponid}")->execute()->current();
            $totalprice = Model_Coupon::get_order_totalprice($order);
            $ischeck = Model_Coupon::check_samount($couponid, $totalprice, $order['typeid'], $order['productautoid'],strtotime( $order['usedate']));
            if ($ischeck['status'] == 1)
            {
                Model_Coupon::add_coupon_order($cid, $order['ordersn'], $totalprice, $ischeck, $couponid);
            }
            else
            {
                $this->send_datagrams($this->client_info['id'], array('status' => false, 'msg' => 'coupon  verification failed!'), $this->client_info['secret_key']);
                exit;
            }
        }
        //$pay_way = $this->request_body->content->pay_way;
        $pay_way = $suitInfo['pay_way'];
        if ($pay_way)
        {
            $order['pay_way'] = $pay_way;
        }
        //$need_confirm = $this->request_body->content->need_confirm;
        $need_confirm = $suitInfo['need_confirm']?$suitInfo['need_confirm']:0;
		$order['need_confirm']=$need_confirm;
        $order['status']=$need_confirm==1?0:1;

        $auto_close_time = $suitInfo['auto_close_time'] ? $suitInfo['auto_close_time'] : 0;
        if ($auto_close_time)
        {
            $order['auto_close_time'] = $auto_close_time + time();;
        }

		// 游客信息
        $tourist = $this->request_body->content->tourist;
        // 订单来源 1PC,2WAP,3小程序,4平台添加
        $order['source'] = 3;
        if ($order['memberid'])
        {
            $out = St_Product::add_order($order,'Model_Techan',$order);
            if ($out)
            {
                $order_id = DB::select('id')->from('member_order')->where('ordersn', '=', $order['ordersn'])->execute()->get('id');
                $order_info = Model_Member_Order::order_info($order['ordersn']);
                $order_info['orderid'] = $order_id;
				$order_info['need_confirm'] = $need_confirm;
                //订单结算信息表数据更新
                Model_Member_Order_Compute::update($order['ordersn']);
				//游客信息保存
				$arr = array();
				foreach($tourist as $k => $v)
                {
					$arr['orderid'] = $order_id;
                    $arr['tourername'] = $v->tourername;
                    $arr['sex'] = $v->sex;
                    $arr['mobile'] = $v->mobile;
                    $arr['cardtype'] = $v->cardtype;
                    $arr['cardnumber'] = $v->cardnumber;
					$query = DB::insert('member_order_tourer', array_keys($arr))->values(array_values($arr))->execute();
				}

                $result = array(
                    'status' => true,
                    'orderinfo' => $order_info
                );
                St_Product::event($ordersn);
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
            else
            {
                $result = array(
                    'status' => false,
                    'msg' => $out['msg']
                );
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

            }
        }


    }

    /**
     * 获取热门目的地
     */
    public function action_hot_city()
    {
        $result = Model_Api_Standard_Techan::hot_dest();
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 按目的地关键词搜索
     */
    public function action_search_city()
    {
        $keyword = St_Filter::remove_xss($this->request_body->content->keyword);
        if (!empty($keyword))
        {
            $result = Model_Api_Standard_Techan::search_dest($keyword);

            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }


    }

    //关键词搜索
    public function action_query_by_keyword()
    {
        $keyword = $this->request_body->content->keyword;
        $p = intval($this->request_body->content->p) or $p = 1;
        $pagesize = intval($this->request_body->content->pagesize) or $pagesize = 10;
        $route_array = array(
            'pinyin' => 'techan',
            'keyword' => $keyword,
            'typeid' => 5
        );
        $searchcode = St_String::split_keyword($keyword);
        $result = Model_Global_Search::search_result($route_array, $searchcode, $p, $pagesize);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //首页推荐
    public function action_index_recommend()
    {
        $p = intval($this->request_body->content->p) or $p = 1;
        $pagesize = intval($this->request_body->content->pagesize) or $pagesize = 4;
        $result = Taglib_Techan::query(array('flag' => 'order', 'row' => $pagesize));
        foreach ($result as &$item)
        {
            $item['litpic'] = Common::img($item['litpic']);
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //查询条件
    public function action_query_condition()
    {
        $result = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量优先'),
                array('id' => 4, 'name' => '人气推荐')
            ),
            'price' => array('name' => '价格', 'child' => array()),
            'attribute' => array(),
        );
        //价格
        $result['price']['child'] = DB::select()->from('techan_pricelist')->where('webid', '=', 0)->execute()->as_array();
        foreach ($result['price']['child'] as &$row)
        {
            if ($row['min'] != '' && $row['max'] != '')
            {
                $row['name'] = Currency_Tool::symbol() . $row['min'] . '-' . Currency_Tool::symbol() . $row['max'];
            }
            else if ($row['min'] == '')
            {
                $row['name'] = Currency_Tool::symbol() . $row['max'] . '以下';
            }
            else if ($row['max'] == '')
            {
                $row['name'] = Currency_Tool::symbol() . $row['min'] . '以上';
            }
        }
        $result['attribute'] = DB::select('id', array('attrname', 'name'))->from('techan_attr')->where('pid', '=', 0)->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();
        foreach ($result['attribute'] as &$item)
        {
            $item['child'] = DB::select('id', array('attrname', 'name'))->from('techan_attr')->where('pid', '=', $item['id'])->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();

        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    public function action_general_query()
    {
        $params = array(
            'pagesize' => $this->request_body->content->pagesize,
            'keyword' => $this->request_body->content->keyword
        );
        $path = $this->request_body->content->path;
        list($params['destpy'], $params['priceid'], $params['sorttype'], $params['attrid'], $params['page']) = explode('-', $path);

        $result = Model_Api_Standard_Techan::search($params);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
	// 获取游客信息是否开启
	public function action_get_tourists()
	{
        $suitid = $this->request_body->content->suitid;
        $suitInfo=Model_Techan_Suit::suit_info($suitid);
		//$result = DB::select()->from('sysconfig')->where('varname', '=', 'cfg_plugin_techan_usetourer')->execute()->current();
        $result['value']=$suitInfo['fill_tourer_type'];
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
	}

    /**
     * 热门目的地
     */
    public function action_get_index_dest()
    {
        $arr = Model_Destinations::get_channel_nav(0, 10, 5);
        $this->send_datagrams($this->client_info['id'], $arr, $this->client_info['secret_key']);
    }

    /**
     * 首页属性
     */
    public function action_get_index_attr()
    {
        $arr = Model_Api_Standard_System::get_index_attr(5);
        $this->send_datagrams($this->client_info['id'], $arr, $this->client_info['secret_key']);
    }

    /**
     * 根据目的地获取产品
     */
    public function action_get_dest_list()
    {
        $destid = $this->request_body->content->destid;
        $offset = $this->request_body->content->page;
        $row = $this->request_body->content->pagesize;
        $offset = empty($offset) ? 0 : $offset*$row;
        $arr = Taglib_Techan::query(array('flag' => 'mdd','destid' => $destid,'offset' => $offset,'row' => $row));
        foreach($arr as &$item){
            $item['litpic'] = Common::img($item['litpic']);
        }
        $this->send_datagrams($this->client_info['id'], $arr, $this->client_info['secret_key']);
    }
}